<template>
    <div class="admin-page">
        <div class="page-header">
            <div class="table-header">
                <div class="table-actions">
                    <el-button type="primary" @click="handleAddAdmin" size="small" icon="el-icon-plus">添加渠道
                    </el-button>
                </div>

            </div>
            <div style="display: flex;justify-content: space-between">
                <div style="display: flex; flex-wrap: wrap; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <div style="display: flex;text-align: center;line-height: 36px;" class="grid-content bg-purple">
                        渠道名称:
                        <el-input v-model="form.search" size="small"
                                  style="width: 70%;margin-left: 10px;"></el-input>
                    </div>
                </div>
                <div style="display: flex; align-items: center; gap: 15px; margin-bottom: 15px;">
                    <el-button type="primary" size="mini" @click="toSearch">搜索</el-button>
                    <el-button type="success" size="mini" @click="reset">重置</el-button>
                </div>
            </div>
            <el-table  height="560" class="1111" :data="adminList" border style="width: 100%;overflow-y: auto"
                      :header-cell-style="{background:'#FAFAFA',color:'#666', fontSize:'13px'}" size="small">
                <el-table-column align="center" prop="id" label="ID"/>
                <el-table-column align="center" prop="name" label="渠道名"/>
                <el-table-column  align="center" label="图片信息" >
                    <template slot-scope="scope">
                        <div >
                            <span>{{ scope.row.thumb }}</span>
                            <div style="margin-left: 20px; text-align: center;">
                                <div @click="showQRCodeDialog(baseUrl + scope.row.content)">
                                    <qrcode-vue :value="baseUrl + scope.row.content" :size="50" level="H"/>
                                </div>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="content" label="渠道地址">
                    <template slot-scope="scope">
                        <div style="display: flex; align-items: center;">
                            <div style="margin-left: 20px; text-align: center;">
                                {{ baseUrl + scope.row.content }}
                            </div>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column align="center" label="操作" width="300">
                    <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="handleEdit(scope.row)" icon="el-icon-edit">编辑
                        </el-button>
                        <el-button type="text" size="mini" @click="handleDelete(scope.row)" icon="el-icon-delete"
                                   class="delete-btn">删除
                        </el-button>
<!--                        <el-button type="success" size="small" @click="handleStateChange(scope.row)"
                                   :style="{ backgroundColor: scope.row.state === 0 ? 'red' : '#67c23a' }">
                            {{ scope.row.state === 0 ? '隐藏' : '显示' }}
                        </el-button>-->
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                           :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                           layout="total,  pager, next, jumper" :total="total"/>
            <!-- 添加商品对话框 -->
            <el-dialog title="添加渠道" :visible.sync="addDialogVisible" width="700px" :close-on-click-modal="false">
                <el-form :model="adminForm" :rules="adminRules" ref="adminForm" label-width="100px" size="small">
                    <el-form-item label="渠道名" prop="name">
                        <el-input style="width: 90%;" v-model="adminForm.name"/>
                    </el-form-item>
                    <el-form-item label="合并数字" prop="merge_id">
                        <el-input style="width: 90%;" v-model="adminForm.merge_id"/>
                    </el-form-item>

<!--                    <el-form-item label="是否显示">-->
<!--                        <el-radio-group v-model="adminForm.state">-->
<!--                            <el-radio :label="1">显示</el-radio>-->
<!--                            <el-radio :label="0">隐藏</el-radio>-->
<!--                        </el-radio-group>-->
<!--                    </el-form-item>-->

                    <el-form-item label="是否测试">
                        <el-radio-group v-model="adminForm.is_divide">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="2">否</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="参与分红等级">
<!--                        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>-->
<!--                        <div style="margin: 15px 0;"></div>-->
                        <el-checkbox-group v-model="checkedLevels" @change="handleCheckedCitiesChange">
                            <el-checkbox v-for="(city, key) in cities" :label="parseInt(key)" :key="key">{{city}}</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false" size="mini">取消</el-button>
                    <el-button type="primary" @click="submitForm" size="mini">确定</el-button>
                </div>
            </el-dialog>
            <!-- 编辑商品对话框 -->
            <el-dialog title="编辑商品" :visible.sync="editDialogVisible" width="700px" :close-on-click-modal="false">
                <el-form :model="adminForm" :rules="adminRules" ref="adminForm" label-width="100px" size="small">
                    <el-form-item label="渠道名" prop="name">
                        <el-input style="width: 90%;" v-model="adminForm.name"/>
                    </el-form-item>

                    <el-form-item label="合并ID" prop="merge_id">
                        <el-input style="width: 90%;" v-model="adminForm.merge_id"/>
                    </el-form-item>

<!--                    <el-form-item label="是否显示">-->
<!--                        <el-radio-group v-model="adminForm.state">-->
<!--                            <el-radio :label="1">显示</el-radio>-->
<!--                            <el-radio :label="0">隐藏</el-radio>-->
<!--                        </el-radio-group>-->
<!--                    </el-form-item>-->

                    <el-form-item label="是否测试">
                        <el-radio-group v-model="adminForm.is_divide">
                            <el-radio :label="1">是</el-radio>
                            <el-radio :label="2">否</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="参与分红等级">
<!--                        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>-->
<!--                        <div style="margin: 15px 0;"></div>-->
                        <el-checkbox-group v-model="checkedLevels" @change="handleCheckedCitiesChange">
                            <el-checkbox v-for="(city, key) in cities" :label="parseInt(key)" :key="key">{{city}}</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>

                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="editDialogVisible = false" size="mini">取消</el-button>
                    <el-button type="primary" @click="submitForm" size="mini">确定</el-button>
                </div>
            </el-dialog>
            <!-- 二维码放大弹窗 -->
            <el-dialog title="二维码" class="test" :visible.sync="qrCodeDialogVisible" width="300px" :close-on-click-modal="true">
                <div style="text-align: center;">
                    <qrcode-vue :value="currentQRCode" :size="200" level="H"/>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import {mapState} from "vuex";
import QrcodeVue from 'qrcode.vue';

export default {
    data() {
        return {
            checkAll: true,
            checkedLevels: [4, 5, 6, 7],
            checkedCities: [4, 5, 6, 7],
            cities: [],
            isIndeterminate: false,
            adminList: [],
            currentPage: 1,
            pageSize: 25,
            total: 0,
            form: {
                search: "",
                clas_id: "",
            },
            addDialogVisible: false,
            editDialogVisible: false,
            adminForm: {
                name: '',
                type: 3,
                is_divide: 2,
                merge_id: '',
                divide_path: '4,5,6,7'
            },
            adminRules:
                {
                    name: [{required: true, message: '请输入渠道名称', trigger: 'blur'}],
                    merge_id: [{required: true, message: '请输入合并ID', trigger: 'blur'}]
                },
            statusList:
                [
                    {
                        id: 1,
                        name: "显示"
                    }, {
                    id: 0, name: '隐藏'
                }
                ],
            imageUrl:
                '',
            imageUrl1:
                '',
            baseUrl: this.$appConfig.imgPath + 'pagesAuth/public/login/index?source=2&re_code=',
            qrCodeDialogVisible: false,
            currentQRCode: ''
        };
    },
    mounted() {
        this.fetchAdminList();
        this.getAllLevel();
    },
    computed: {
        ...mapState(["userInfo"]),
        qrcodeValue() {
            return this.baseUrl + (this.adminForm.content || '');
        }
    },
    components: {
        QrcodeVue
    },
    methods: {
        // handleCheckAllChange(val) {
        //     this.adminForm.divide_path = val ? [4, 5, 6, 7] : [];
        //     this.isIndeterminate = false;
        //     this.checkAll = val;
        // },
        handleCheckedCitiesChange(value) {
            this.checkedLevels = value;
            let checkedCount = value.length;
            this.checkAll = checkedCount === Object.keys(this.cities).length;
            this.isIndeterminate = checkedCount > 0 && checkedCount < Object.keys(this.cities).length;
            // Convert array to string - use only the selected values, not default values
            this.adminForm.divide_path = this.checkedLevels.join(',');
            console.log('Current divide_path:', this.adminForm.divide_path);
        },
        getAllLevel(){
            this.$http.get('/admin/User/getUserUp').then(result => {
                if (result.code === 200) {
                    this.cities = {
                        ...this.cities,
                        ...result.data
                    };
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        fetchAdminList() {
            const params = {
                type: 3,
                page: this.currentPage,
                limit: this.pageSize
            };
            this.$http.get('/admin/single/lists', {params}).then(result => {
                console.log(result)
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.adminList = newListData;
                    this.total = result.data.total || newListData.length;
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.fetchAdminList();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.fetchAdminList();
        },
        handleAddAdmin() {
            this.adminForm = {
                name: '',
                type: 3,
                is_divide: 2,
                merge_id: '',
                divide_path: ''
            };
            this.checkedLevels = [];
            this.checkAll = false;
            this.isIndeterminate = false;
            this.$refs.adminForm && this.$refs.adminForm.clearValidate();
            this.addDialogVisible = true;
        },
        handleEdit(row) {
            // 调用接口获取详细数据
            this.$http.get(`/admin/single/edit`, {params: {id: row.id}}).then(result => {
                if (result.code == 200) {
                    this.adminForm = {
                        id: row.id,
                        name: row.name,
                        type: row.type,
                        is_divide: row.is_divide,
                        merge_id: row.merge_id !== undefined ? row.merge_id : '',
                        divide_path: row.divide_path || ''
                    };

                    // Convert string to array for checkbox display
                    if (typeof this.adminForm.divide_path === 'string' && this.adminForm.divide_path) {
                        this.checkedLevels = this.adminForm.divide_path.split(',').map(item => parseInt(item));
                    } else {
                        this.checkedLevels = [];
                    }

                    this.editDialogVisible = true;
                    // 等待 DOM 更新后设置表单验证状态
                    this.$nextTick(() => {
                        this.$refs.adminForm && this.$refs.adminForm.clearValidate();
                    });
                } else {
                    this.$message.error(result.msg || '获取详情失败');
                }
            }).catch(error => {
                console.error('获取详情失败:', error);
                this.$message.error('获取详情失败');
            });
        },

        toSearch() {
            const params = {
                ...this.form,
                type: 3,
                limit: 1
            };
            this.$http.get('/admin/single/lists', {params}).then(result => {
                if (result.code === 200) {
                    const dataObj = result.data.data;
                    const newListData = [];
                    for (const key in dataObj) {
                        if (dataObj.hasOwnProperty(key)) {
                            newListData.push(dataObj[key]);
                        }
                    }
                    this.adminList = newListData;
                    this.total = result.data.total || newListData.length;
                } else {
                    this.$message.error(result.msg);
                }
            });
        },
        reset() {
            this.form = {}
            this.fetchAdminList()
        },
    /*    handleStateChange(row) {
            const newState = row.state === 1 ? 0 : 1;
            this.$http.post('/admin/single/del', {
                name: row.name,
                type: row.type,
                thumb: row.thumb,
                content: row.content,
                is_divide: row.is_divide,
                id: row.id,
                state: newState
            }).then(result => {
                if (result.code === 200) {
                    this.$message.success('状态更新成功');
                    this.fetchAdminList();
                } else {
                    this.$message.error(result.msg || '状态更新失败');
                }
            });
        },*/
        handleDelete(data) {
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 用户点击了确定按钮
                this.$http.post('/admin/single/del', {
                    id: data.id,
                    // state: "-1"
                }).then(result => {
                    if (result.code === 200) {
                        this.$message.success(result.msg);
                        this.fetchAdminList();
                    } else {
                        this.$message.error(result.msg);
                    }
                });
            }).catch(() => {
                // 用户点击了取消按钮
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },


        showQRCodeDialog(url) {
            this.currentQRCode = url;
            this.qrCodeDialogVisible = true;
        },

        submitForm() {
            console.log(this.adminForm);
            this.$refs.adminForm.validate(valid => {
                if (valid) {
                    // Ensure divide_path is a string from checkedLevels
                    this.adminForm.divide_path = this.checkedLevels.join(',');

                    // 假设后端接口需要 id 来确定要编辑的记录，这里将 adminForm 中的 id 一起传递
                    this.$http.post('/admin/single/edit', this.adminForm).then(result => {
                        if (result.code === 200) {
                            this.$message.success(result.msg);
                            this.addDialogVisible = false;
                            this.editDialogVisible = false;
                            this.fetchAdminList();
                        } else {
                            this.$message.error(result.msg);
                        }
                    });
                }
            });
        }
    }
};
</script>
<style lang="less" scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}

/deep/ .el-dialog__header {
    padding: 10px !important;
    text-align: center;
}

.admin-page {
    padding: 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);

    .page-header {
        margin-bottom: 24px;
        padding-bottom: 16px;
        border-bottom: 1px solid #f0f2f5;

        .header-title {
            font-size: 20px;
            font-weight: 600;
            color: #1f2937;
            line-height: 1.4;
        }
    }

    .table-header {
        margin-bottom: 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .table-title {
            font-size: 16px;
            font-weight: 500;
            color: #374151;
        }

        .table-actions {
            .el-button {
                margin-left: 12px;
                transition: all 0.3s;

                &:hover {
                    transform: translateY(-1px);
                }
            }
        }
    }

    .el-tabs {
        margin-top: 16px;

        :deep(.el-tabs__header) {
            margin-bottom: 28px;
            border-bottom: 2px solid #f0f2f5;
        }

        :deep(.el-tabs__item) {
            font-size: 15px;
            padding: 0 28px;
            height: 44px;
            line-height: 44px;
            transition: all 0.3s;

            &.is-active {
                color: #2563eb;
                font-weight: 500;
            }

            &:hover {
                color: #2563eb;
            }
        }

        :deep(.el-tabs__active-bar) {
            height: 2px;
            background-color: #2563eb;
            transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
        }
    }

    .el-table {
        margin-top: 12px;
        border-radius: 8px;
        overflow: hidden;

        :deep(th) {
            background-color: #f9fafb !important;
            font-weight: 500;
            color: #4b5563;
        }

        :deep(td) {
            padding: 12px 0;
        }

        .delete-btn {
            color: #dc2626;
            transition: all 0.3s;

            &:hover {
                color: #ef4444;
            }
        }
    }

    .el-pagination {
        margin-top: 24px;
        padding: 12px 0;
        text-align: right;

        :deep(.el-pagination__total) {
            margin-right: 12px;
        }

        :deep(.btn-prev),
        :deep(.btn-next) {
            border-radius: 4px;
            background-color: #fff;
        }

        :deep(.el-pager li) {
            border-radius: 4px;
            background-color: #fff;

            &.active {
                background-color: #2563eb;
            }
        }
    }

    .el-dialog {
        border-radius: 12px;
        overflow: hidden;
        max-height: 90vh;
        display: flex;
        flex-direction: column;

        :deep(.el-dialog__header) {
            padding: 20px 24px !important;
            border-bottom: 1px solid #f0f2f5;
            margin: 0;

            .el-dialog__title {
                font-size: 18px;
                font-weight: 600;
                color: #1f2937;
            }
        }

        :deep(.el-dialog__body) {
            padding: 32px 24px;
            flex: 1;
            overflow-y: auto;

            .el-form-item {
                .el-input,
                .el-select {
                    width: 320px;
                }
            }
        }

        :deep(.el-tree) {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #DCDFE6;
            border-radius: 4px;
            padding: 10px;
        }

        :deep(.el-dialog__footer) {
            padding: 16px 24px;
            border-top: 1px solid #f0f2f5;
        }

        :deep(.el-form-item__label) {
            font-weight: 500;
            color: #374151;
        }

        :deep(.el-button) {
            padding: 8px 20px;
            transition: all 0.3s;

            &:hover {
                transform: translateY(-1px);
            }
        }
    }
}

.tip-text {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
    display: block;
}

/deep/ .el-tab-pane {
    height: 650px;
    overflow-y: auto;
}

</style>


<el-dialog title="二维码" :visible.sync="qrCodeDialogVisible" width="300px" :close-on-click-modal="false">
<div style="text-align: center;">
    <qrcode-vue :value="currentQRCode" :size="200" level="H"/>
</div>
</el-dialog>
}



